package client.comm.baoding

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.os.Process
import android.util.Log
import androidx.databinding.ViewDataBinding
import client.comm.baoding.dialog.AgainEnterPrivacyDialog
import client.comm.baoding.dialog.MsgTitleDialog
import client.comm.baoding.dialog.UpDateDialog
import client.comm.baoding.fragment.ProtocolDialogFragment
import client.comm.baoding.ui.LoginActivity
import client.comm.baoding.ui.MainActivity
import client.comm.baoding.ui.vm.LauncherViewModel
import client.comm.baoding.utils.HandlerTip
import client.comm.baoding.utils.PreferencesManager
import client.comm.commlib.ContextProvider
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.SharedUtil
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions


class LauncherActivity : BaseMiddleActivity<LauncherViewModel, ViewDataBinding>(),
    EasyPermissions.PermissionCallbacks {

    internal val RC_SMS = 0x88

    override fun getLayout(): Int {
        return R.layout.activity_launcher
    }

    override fun initViewModel(): LauncherViewModel = createViewModel()

    fun handle() {
        if (!SharedUtil.read("token", "").isNullOrEmpty()) {
//            val userState = SharedUtil.read("userState", -1)
//            if (userState == 1) {
            val intent =
                Intent(this@LauncherActivity, MainActivity::class.java)
            startActivity(intent)
//            } else if (userState == 0) {
//                val intent =
//                    Intent(this@LauncherActivity, UpGradeActivity::class.java)
//                startActivity(intent)
//            } else {
//                val intent =
//                    Intent(this@LauncherActivity, LoginActivity::class.java)
//                startActivity(intent)
//            }

        } else {
            val intent =
                Intent(this@LauncherActivity, LoginActivity::class.java)
            startActivity(intent)
        }
        finish()
    }

    override fun initData() {
        requestExternalStorage()
//        startActivity(Intent(this, TestActivity::class.java))
    }

    override fun observerUI() {
        toActivity()

    }

    private fun toActivity() {
        /*if (PreferencesManager.getInstance().getProtcal()) {
            val bundle = Bundle()
            bundle.putInt("type", 1)
            val operationDialogFragment =
                ProtocolDialogFragment()
            operationDialogFragment.setArguments(bundle)
            operationDialogFragment.setOnOperationConfirmListen {
                PreferencesManager.getInstance().setProtcal(false)
                toActivity()
            }
            operationDialogFragment.setOnOperationCancelListen {

                AgainEnterPrivacyDialog(this).apply {
                    title = "若您不同意本隐私协议政策，很遗憾我们将无法为您提供服务，要不要在想想？"
                    left = {
                        finish()
                    }
                    ok = {
                        toActivity()
                    }
                    leftTxt = "退出应用"
                    okTxt = "再次查看"
                }.show()


            }
            operationDialogFragment.show(supportFragmentManager, "operationDialogFragment")
            return
        }*/
        HandlerTip.getInstance().postDelayed(
            milliseconds
        ) { toActivityTrue() }
    }

    private val milliseconds = 0


    private fun toActivityTrue() {
        onVersion()
    }


    private fun onVersion() {
        viewModel.versionRet.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    data?.let {
                        2
                        if (it.state == 1) {//有新版本
                            ContextProvider.get().activity?.apply {
                                UpDateDialog(this, viewModel, it.url).apply {
                                    errorFun = {
                                        toast("下载失败，请重新下载")
                                        show()
                                    }
                                }.show()
                            }
                        } else if (it.state == 2) {
                            toast("系统维护")
                            Process.killProcess(0)
                        } else {
                            handle()
                        }
                    }
                } else {

                    MsgTitleDialog(this@LauncherActivity).apply {
                        title = "获取版本失败，请重新获取"
                        okTxt = "重新获取"
                        cancleTxt = "退出"
                        cancle = {
                            finish()
                        }
                        setCancelable(false)
                        setCanceledOnTouchOutside(false)
                        ok = {
                            viewModel.getVersion()
                        }
                    }.show()
                }
            }
        })
    }


    fun requestExternalStorage() {
        if (!EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            EasyPermissions.requestPermissions(
                this,
                "请开启读写权限(用于读取和保存图片)？",
                RC_SMS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
//            return
        } else {
            //有權限
            viewModel.getVersion()

        }

//        if (EasyPermissions.hasPermissions(
//                this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            )
//        ) {//有權限
//            viewModel.getVersion()
//        } else {
//            if (EasyPermissions.somePermissionDenied(
//                    this,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE
//                )
//            ) {
//                AppSettingsDialog.Builder(this).setTitle("请开启权限").setRationale("跳转设置界面").build()
//                    .show()
//            } else {
//                //为了您能够正常使用其功能
//                EasyPermissions.requestPermissions(
//                    this, "请开启权限",
//                    RC_SMS,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE
//                )
//            }
//        }

    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        // 请求权限已经被授权
        if (requestCode == RC_SMS) {
            if (perms.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                viewModel.getVersion()
            }
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        // 请求权限被拒绝
//        AppSettingsDialog.Builder(this)
//            .setTitle("申请权限")
//            .setRationale("没有相关权限应用将无法正常运行，点击确定进入权限设置界面来进行更改")
//            .build().show()
//        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
//
//        }
//        toast( "权限被拒绝")
        Log.i(C_TAG, "权限被拒绝")
        viewModel.getVersion()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

//        when (requestCode) {
//            RC_SMS -> {
//                if (EasyPermissions.hasPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//                    requestExternalStorage()
//                } else {
//                    Log.i(C_TAG, "权限被拒绝")
//                    viewModel.getVersion()
//                }
//            }
//        }
    }

}